import 'package:flutter/material.dart';
import 'package:manual/theme/loading_ovaerlay_theme.dart';

class LoadingOverlay {
  static OverlayEntry? _overlayEntry;

  /// 显示加载框
  static void show({
    required BuildContext context,
    double iconSize = 48.0, // 图标大小
    double padding = 24.0, // 图标四周的 padding
  }) {
    // 如果已经显示，避免重复添加
    if (_overlayEntry != null) return;

    // 获取 OverlayState
    final overlayState = Overlay.of(context);

    // 获取主题中的 LoadingOverlay 样式
    final theme = Theme.of(context).extension<LoadingOverlayTheme>()!;
    final backgroundColor = theme.backgroundColor;
    final loadingColor = theme.loadingColor;

    // 创建 OverlayEntry
    _overlayEntry = OverlayEntry(
      builder: (BuildContext context) {
        return Positioned(
          // 居中显示
          top: MediaQuery.of(context).size.height / 2 - iconSize / 2 - padding,
          left: MediaQuery.of(context).size.width / 2 - iconSize / 2 - padding,
          child: Material(
            color: Colors.transparent,
            child: Container(
              padding: EdgeInsets.all(padding),
              decoration: BoxDecoration(
                color: backgroundColor,
                borderRadius: BorderRadius.circular(12.0),
                // boxShadow: const [
                //   BoxShadow(
                //     color: Colors.black26,
                //     blurRadius: 4.0,
                //     spreadRadius: 2.0,
                //   ),
                // ],
              ),
              child: SizedBox(
                width: iconSize,
                height: iconSize,
                child: CircularProgressIndicator(
                  strokeWidth: 2.0,
                  color: loadingColor,
                ),
              ),
            ),
          ),
        );
      },
    );

    // 显示 OverlayEntry
    overlayState.insert(_overlayEntry!);
  }

  /// 隐藏加载框
  static void hide() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }
}
